//
//  EditAddressController.m
//  cooba-iOS
//
//  Created by 郭四虎 on 16/4/25.
//  Copyright © 2016年 YouKu. All rights reserved.
//

#import "EditAddressController.h"
#define wid (WIDTH-40)
@interface EditAddressController ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (strong, nonatomic) UIView *vi;

@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *phone;
@property (weak, nonatomic) IBOutlet UITextField *postcode;

@property (weak, nonatomic) IBOutlet UIButton *address;
@property (weak, nonatomic) IBOutlet UITextField *otherAddress;


@property (weak, nonatomic) IBOutlet UIPickerView *picker;
@property (strong, nonatomic) IBOutlet UIView *backView;

@property (strong, nonatomic) NSDictionary *pickerDic;
@property (strong, nonatomic) NSMutableArray *provinceArray;
@property (strong, nonatomic) NSMutableArray *cityArray;
@property (strong, nonatomic) NSMutableArray *townArray;
@property (strong, nonatomic) NSMutableArray *selectedArray;

@end

@implementation EditAddressController

- (UIView *)vi
{
    if (!_vi) {
        _vi = [[UIView alloc]initWithFrame:SCREEN];
        _vi.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
        
        [_vi addSubview:self.backView];
        self.backView.width = WIDTH;
        self.backView.height = 180*SCALEX;
        self.backView.y = HEIGHT - 180*SCALEX;
        
    }
    return _vi;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (_model) {
        _name.text = _model.user_name;
        _phone.text = _model.phone;
        _postcode.text = _model.post_code;
        [_address setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        NSArray *arr = [_model.address componentsSeparatedByString:@"@@"];
        
        [_address setTitle:arr[0] forState:UIControlStateNormal];
        if (arr.count == 2) {
            _otherAddress.text = arr[1];
        }
        
        self.title = @"修改地址信息";
    }else{
        self.title = @"添加地址信息";
        [_name becomeFirstResponder];
    }
    
    _provinceArray = [NSMutableArray array];
    _cityArray = [NSMutableArray array];
    _townArray = [NSMutableArray array];
    _selectedArray = [NSMutableArray array];
    [self getPickerData];
}
- (IBAction)chooseAddress:(id)sender {
    
    [self.view endEditing:YES];
    [self.view addSubview:self.vi];
    
}

- (BOOL)isPostcode:(NSString *)postcode
{
    NSString *str = @"^[1-9]\\d{5}$";
    
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",str];
    
    BOOL isRight = [pre evaluateWithObject:postcode];
    
    return isRight;
}

- (IBAction)editAddress:(id)sender {
    
    if (![Myuser valiMobile:_phone.text]) {
        Message(@"请填写正确的手机号");
        return;
    }
    
    if (![self isPostcode:_postcode.text]) {
        Message(@"请填写正确的邮编");
        return;
    }
    
    if (!_otherAddress.text.length||!_address.currentTitle) {
        Message(@"请填写地址信息");
        return;
    }
    
    NSString *address = [NSString stringWithFormat:@"%@@@%@",_address.currentTitle,_otherAddress.text];
    
    NSDictionary *parameter;
    if (_model) {
        parameter = @{@"id":_model.addressid,@"login_id":[Myuser sharedUser].login_id,@"address":address,@"post_code":_postcode.text,@"user_name":_name.text,@"phone":_phone.text};
    }else{
        parameter = @{@"login_id":[Myuser sharedUser].login_id,@"address":address,@"post_code":_postcode.text,@"user_name":_name.text,@"phone":_phone.text};
    }
    
    [MyAFN POST:CHANGEADDRESS parameters:parameter block:^(id responseObject) {
        
        if ([[responseObject objectForKey:@"status"]integerValue]) {
            if (!_model) {
                _model = [[AddressModel alloc]init];
            }
            _model.addressid = [responseObject objectForKey:@"id"];
            _model.address = address;
            _model.user_name = _name.text;
            _model.phone = _phone.text;
            _model.post_code = _postcode.text;
            self.changeAddress(_model);
    
            [self.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:@(YES) afterDelay:0.5];
        }else{
            [self.view performSelector:@selector(Message:) withObject:[responseObject objectForKey:@"msg"] afterDelay:0.5];
        }
    } error:^(NSError *error) {
        
    } fromController:self];
}
- (IBAction)cancle:(id)sender {
    [self.vi removeFromSuperview];
}
- (IBAction)ensure:(id)sender {
    
    NSString *province = [self.provinceArray objectAtIndex:[self.picker selectedRowInComponent:0]];
    NSArray *city = [self.cityArray objectAtIndex:[self.picker selectedRowInComponent:1]];
    NSString *town = [self.townArray objectAtIndex:[self.picker selectedRowInComponent:2]];
    
    [_address setTitle:[NSString stringWithFormat:@"%@%@%@",province,city,town] forState:UIControlStateNormal];
    [_address setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.vi removeFromSuperview];
}

- (void)getPickerData {
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"];
    self.pickerDic = [[NSDictionary alloc] initWithContentsOfFile:path];
    
    for (NSDictionary *dic in [self.pickerDic objectForKey:@"haha"]) {
        [_provinceArray addObject:dic.allKeys[0]];
    }
    self.selectedArray.array = [[self.pickerDic objectForKey:@"haha"][0] objectForKey:_provinceArray[0]];
    
    if (self.selectedArray.count >0) {
        self.cityArray.array = [self.selectedArray[0]allKeys];
    }
    if (self.cityArray.count>0) {
        self.townArray.array = [self.selectedArray[0] objectForKey:self.cityArray[0]];
    }
    
}

#pragma mark - UIPicker Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.provinceArray.count;
    } else if (component == 1) {
        return self.cityArray.count;
    } else {
        return self.townArray.count;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, wid/3, 30)];
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment = NSTextAlignmentCenter;
    if (component == 0) {
        label.text = [self.provinceArray objectAtIndex:row];
    } else if (component == 1) {
        label.text = [self.cityArray objectAtIndex:row];
    } else {
        label.text = [self.townArray objectAtIndex:row];
    }
    return label;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [self.provinceArray objectAtIndex:row];
    } else if (component == 1) {
        return [self.cityArray objectAtIndex:row];
    } else {
        return [self.townArray objectAtIndex:row];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    return wid/3;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.selectedArray.array = [[self.pickerDic objectForKey:@"haha"][row]objectForKey:[self.provinceArray objectAtIndex:row]];
        if (self.selectedArray.count > 0) {
            self.cityArray.array = [[self.selectedArray objectAtIndex:0] allKeys];
        } else {
            self.cityArray = nil;
        }
        if (self.cityArray.count > 0) {
            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:0]];
        } else {
            self.townArray = nil;
        }
        [pickerView selectRow:0 inComponent:1 animated:YES];
    }
    
    [pickerView reloadComponent:1];
    
    
    if (component == 1) {
        if (self.selectedArray.count > 0 && self.cityArray.count > 0) {
            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:row]];
        } else {
            self.townArray = nil;
        }
        [pickerView selectRow:0 inComponent:2 animated:YES];
    }
    [pickerView reloadComponent:2];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
